package com.ropeok.Utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ropeok.dto.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class JwtUtils {
    private static String SECRET = "token!Q@W#E$R";

    private static int expireTime;

    @Autowired
    private RedisUtil redisUtil;

//定义过期时间为30
    @Value("${jwt.expireTime}")
    public void setExpireTime(int expireTime1){
        JwtUtils.expireTime = expireTime1;
    }


    /**
     * 生产token
     */
    public static String getToken(Map<String, String> map) {
        JWTCreator.Builder builder = JWT.create();
        //payload
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });

        String token = builder.sign(Algorithm.HMAC256(SECRET));//签名,加密方法+盐
//        Calendar instance = Calendar.getInstance();
//        instance.add(Calendar.DATE, 7); //默认7天过期
//        builder.withExpiresAt(instance.getTime());//指定令牌的过期时间
        return token;
    }

    /**
     * 验证token
     */
    public static DecodedJWT verify(String token) {
        //如果有任何验证异常，此处都会抛出异常
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
//        System.out.println("我没异常");
        return decodedJWT;
    }

    public  void refreshToken(UserDto user){
        //重新设置User对象的过期时间，再刷新缓存
        user.setExpireTime(System.currentTimeMillis()+1000L * 60 * expireTime);
        //存入key值，用户信息，
        redisUtil.saveValue(user.getUserid()+"",user,expireTime, TimeUnit.MINUTES);
    }

    public UserDto setTime(UserDto user){
        user.setExpireTime(System.currentTimeMillis()+1000L * 60 * expireTime);
        user.setLoginTime(System.currentTimeMillis());
        return user;
    }

//    /**
//     * 获取token中的 payload
//     */
//    public static DecodedJWT getToken(String token) {
//        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
//        return decodedJWT;
//    }
}
